<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <script>
    function Text(name) {
      this.name = name;
      return 1;
    }

    const t = new Text("xxx");
    console.log(t.name);
    console.log(t);

    function Text2(name) {
      this.name = name;
      console.log(this, "t2this");
      return {
        age: 26,
      };
    }

    const t2 = new Text2("xxx");
    console.log(t2.name, "t2.name");
    console.log(t2, "t2");

    function myNew(func, ...args) {
      const obj = {};
      // 新对象的原型指向构造函数的原型
      obj.__proto__ = func.prototype;
      // 将构造函数的this指向新对象
      let result = func.apply(obj, args);

      return result instanceof Object ? result : obj;
    }

    function Person(name, age) {
      this.name = name;
      this.age = age;
    }

    Person.prototype.say = function () {
      console.log(this.name);
    };

    let per = myNew(Person, "huihui", 123);
    per.say();
    console.log(per);

    // 更现代的实现方式可以用object.create()代替__proto__

    function myNew2(func, args) {
        // const obj = {}
        // obj.__proto__ = func.prototype
     const obj = Object.create(func.prototype)
        let result = func.apply(obj, args)

        return result instanceof Object ? result: obj
    }


    function pro(func, args) {
      const obj = obj.create(func.prototype)
      const result = func.apply(this, args)
      return result instanceof Object ? result : obj
    }

  </script>
  <body>
    <div>手写new操作符</div>
  </body>
</html>
